package com.lx.tomcat.lifecycle;

import java.util.ArrayList;
import java.util.List;

public abstract class LifecycleBase implements Lifecycle{
    private List<LifecycleListener> lifecycleListeners = new ArrayList<>();
    private LifecycleState lifecycleState = LifecycleState.NEW;
    protected abstract void initInternal() throws Exception;
    protected abstract void startInternal() throws Exception;
    protected abstract void stopInternal() throws Exception;
    protected abstract void destroyInternal() throws Exception;

    public LifecycleBase() {
    }

    public LifecycleBase(List<LifecycleListener> lifecycleListeners, LifecycleState lifecycleState) {
        this.lifecycleListeners = lifecycleListeners;
        this.lifecycleState = lifecycleState;
    }

    @Override
    public void addLifecycleListener(LifecycleListener listener) {
        lifecycleListeners.add(listener);
    }

    @Override
    public List<LifecycleListener> findLifecycleListeners() {
        return lifecycleListeners;
    }

    @Override
    public void removeLifecycleListener(LifecycleListener listener) {
        lifecycleListeners.remove(listener);
    }

    protected void fireLifecycleEvent(LifecycleState type, Object data) {
        LifecycleEvent event = new LifecycleEvent(this, type, data);
        System.out.println(event);
        for (LifecycleListener listener : lifecycleListeners) {
            listener.lifecycleEvent(event);
        }
    }

    @Override
    public LifecycleState getState() {
        return lifecycleState;
    }

    public void setLifecycleState(LifecycleState lifecycleState) {
        this.lifecycleState = lifecycleState;
    }

}
